<template>
	<view class="flex flex-column">
		<!-- 头部 -->
		<yHeader :current="0" :screenWidth="screenWidth" :isTabs="false" @Tabs="handleTabs"></yHeader>
		<view class="flex justify-center py-4" style="height: 100%">
			<view class="content bg-white border border-grey shadow">
				<el-tabs v-model="activeName">
					<el-tab-pane label="账号注册" name="first">
						<el-form ref="form" label-width="90px" :rules="rules" :model="form" @submit.native.prevent>
							<el-form-item label="用户名" prop="ID_Name">
								<el-input placeholder="请输入用户名" v-model="form.ID_Name">
								</el-input>
							</el-form-item>
							<el-form-item label="用户身份" prop="ID_Name">
								<el-select @change="change" style="width: 700rpx;" v-model="form.User_Type" clearable placeholder="请选择您的用户身份">
									<el-option v-for="item in identitys" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>
								</el-input>
							</el-form-item>
							<el-form-item label="手机号" prop="User_Number">
								<el-input placeholder="请输入手机号" v-model="form.User_Number" @blur="checkPhone">
								</el-input>
								<transition name="fade">
									<text v-show="isPhone" class="text-danger">手机号已注册</text>
								</transition>
							</el-form-item>
							<el-form-item label="密码" prop="Pass_Ward">
								<el-input show-password placeholder="请输入密码" v-model="form.Pass_Ward" type="password">
								</el-input>
							</el-form-item>
							<el-form-item label="确认密码" prop="ConfirmPassword">
								<el-input show-password placeholder="请输入确认密码" v-model="form.ConfirmPassword"
									type="password">
								</el-input>
							</el-form-item>
							<el-form-item label="验证码" class="input—y" prop="code">
								<el-input placeholder="请输入验证码" class="input—x" v-model="form.code">
								</el-input>
								<el-button v-if="time" @click="sendMessage" type="success">获取验证码</el-button>
								<el-button v-else type="success">{{secend}}</el-button>
							</el-form-item>

							<el-button type="success" class="btn bg-success" @click="saveForm" :disabled="!isAgree"
								:loading="loading">注册</el-button>

							<p>
								<text @click="Login">已有账号?点击登录</text>
							</p>
						</el-form>

						<view class="foot">
							<el-checkbox v-model="isAgree"></el-checkbox>
							<text>
								注册即表示已同意
								<text @click="goAgreement()" class="text-success hover"> 《用户服务协议》</text>
							</text>
						</view>
					</el-tab-pane>
				</el-tabs>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		register,
		checkPhone,
	} from "../../api/login.js";
	import {
		getInquiryIDOriginal,
		getEditAction,
		RedisAdd,
		isPhoneCode
	} from "@/api/global.js";
	import {
		Message
	} from "element-ui";
	const app = getApp();
	import yHeader from "@/components/yHeader.vue";
	import yFooter from "@/components/yFooter.vue";
	export default {
		components: {
			yHeader,
			yFooter,
		},
		data() {
			return {
				loading: false,
				isPhone: false,
				isAgree: false,
				screenWidth: uni.getSystemInfoSync().windowWidth,
				ThemeColors: app.globalData.ThemeColors,
				activeName: "first",
				timer: null,
				time: true,
				secend: 60,
				RandomCode: '',
				form: {
					User_Number: "",
					Pass_Ward: "",
					ID_Name: "",
					User_Type:'',
					Authentication: "",
					ConfirmPassword: "",
					code: "",
				},
				identitys:[{
					id:0,
					name:'商协会'
				},{
					id:1,
					name:'我是买家'
				},{
					id:2,
					name:'我是卖家'
				},],
				rules: {
					ID_Name: [{
						required: true,
						message: "请输入用户名",
						trigger: "blur"
					}],
					User_Number: [{
						required: true,
						message: "请输入手机号",
						trigger: "blur"
					}, {
						pattern: /^1[3456789]\d{9}$/,
						message: '手机号码格式不正确',
						trigger: 'blur'
					}],
					Pass_Ward: [{
						required: true,
						message: "请输入密码",
						trigger: "blur"
					}],
					ConfirmPassword: [{
							required: true,
							message: "请输入确认密码",
							trigger: "blur"
						},
						{
							validator: this.validateConfirmPassword,
							trigger: "blur"
						},
					],
					code: [{
						required: true,
						message: "请输入验证码",
						trigger: "blur"
					}],
				},
			};
		},
		methods: {
			async checkPhone() {
				if (this.form.User_Number == "") {
					this.isPhone = false;
				}
				const res = await checkPhone({
					data: {
						User_Number: this.form.User_Number,
					},
				});
				console.log(res)
				if (res.Status == "success" && this.form.User_Number !== "") {
					this.isPhone = false;
				} else if (res.Status == "fail" && this.form.User_Number !== "") {
					this.isPhone = true;
				}
			},

			validateConfirmPassword(rule, value, callback) {
				if (value !== this.form.Pass_Ward) {
					callback(new Error("两次输入的密码不一致"));
				} else {
					callback();
				}
			},

			handleTabs(url) {
				uni.navigateTo({
					url,
				});
			},
			async register() {
				const res = await register({
					data: {
						Data: JSON.stringify({
							system_user_info: [this.form],
						}),
					},
				});
				this.loading = false
				if (res.Status !== "success") return Message.error("注册失败");
				Message.success("注册成功");
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},
			async CheckCode(data){
				const res = await isPhoneCode({
					data
				})
				if(res.Status=='success'){
					this.loading = true
					this.register();
				}else{
					Message({
						type:'error',
						message:'短信验证码错误'
					})
				}
			},
			saveForm() {
				this.$refs.form.validate((valid) => {
					if (valid) {
						let Data = {
							Code:this.form.code,
							Phone:this.form.User_Number
						}
						this.CheckCode(Data)
					} else {
						Message({
							type: 'error',
							message: '请检查页面表单是否填写正确'
						})
					}
				});
			},
			Login() {
				uni.navigateTo({
					url: "/pages/login/login",
				});
			},
			goAgreement() {
				uni.navigateTo({
					url: '/pages/login/User_Service_Agreement'
				})
			},
			change(){
				if(uni.getStorageSync('userType')!='1'){
					Message({
						type:'info',
						message:'选定身份注册后不会影响您的其他交易行为'
					})
					uni.setStorageSync('userType','1')
				}
			},
			sendMessage() {
				if (this.form.User_Number == '') {
					Message.error("请先输入正确的手机号再点击发送");
					return
				}
				const reg = /^1[3-9]\d{9}$/
				if (!reg.test(this.form.User_Number)) {
					Message.error("请检查手机号格式是否正确!");
					return
				}
				if (this.isPhone) {
					Message.error("您输入的手机号已被注册");
					return
				}
				this.time = false
				this.secend = 60
				this.secend--
				this.timer = setInterval(() => {
					if (this.secend == '01') {
						clearInterval(this.timer)
						this.time = true
						return
					}
					this.secend--
					if (this.secend < 10) {
						this.secend = '0' + this.secend
					}
				}, 1000)
				let code = '';
				for (let i = 0; i < 6; i++) {
					code += parseInt(Math.random() * 10);
				}
				this.RandomCode = code
				uniCloud.callFunction({
					name: 'sendSms', //对应的云函数名
					data: {
						phone: this.form.User_Number,
						data: {
							name: '众菌联',
							code: this.RandomCode, //随机生成的验证码，如123456
							action: '注册', //校验类型为“注册”
							expMinute: '5', //短信的有效期，5分钟
						}
					}
				}).then(res => {
					if (res.success) {
						Message.success("短信已发送");
						this.RedisPush()
					}
				}).catch(msg => {
					console.log(msg)
					Message.error("系统错误!请稍后重试");
				});
			},
			async RedisPush(){
				const res = await RedisAdd({
					data:{
						Key:'zjl_'+this.form.User_Number,
						Main:JSON.stringify({
							code:this.RandomCode,
							expires_in:parseInt(new Date().getTime()/1000)+300
						}),
						Expire:300,
					}
				})
				console.log(res)
			},
		},
	};
</script>

<style lang="scss" scoped>
	.content {
		width: 500px;
		//   height: 426px;
		padding: 10px 30px 16px;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-around;

		.el-tabs {
			width: 100%;
			height: 100%;
		}

		.btn {
			width: 100%;
			margin-top: 40rpx;
			background-color: #28a745 !important;
		}

		p {
			display: flex;
			margin: 20px 0;
			line-height: 17px;
			font-size: 12px;
			color: #646464;
			justify-content: space-between;

			text {
				cursor: pointer;
			}

			text:hover {
				color: #28a745;
			}
		}

		.foot {
			margin: 10px 0 0 0;

			.el-checkbox {
				margin: 0 5px 0 0;
			}

			font-size: 12px;
			color: #646464;
		}

		.input—x {
			.el-input__inner {
				border-radius: 10px 0 0 10px;
			}
		}

		/deep/ .el-form-item__content {
			display: flex;
			position: relative;
		}

		.text-danger {
			color: #f56c6c;
			font-size: 24rpx;
			line-height: 1;
			padding-top: 8rpx;
			position: absolute;
			top: 100%;
			left: 0;
			// top: 32px;
			// left: 10px;
		}

		.fade-enter-active,
		.fade-leave-active {
			transition: opacity 0.2s;
		}

		.fade-enter,
		.fade-leave-to {
			opacity: 0;
		}
	}

	.hover:hover {
		text-decoration: underline;
		cursor: pointer;
	}
</style>